package com.tuanbiao.utils;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ThreadMainTaskManager {

    public interface OnThreadMainTaskCallback<T>{
        T doThreadTask();
        void doMainTask(T t);
    }

    public static <T> Disposable startTask(OnThreadMainTaskCallback<T> callback){
       return Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(ObservableEmitter<T> emitter) throws Exception {
                emitter.onNext(callback.doThreadTask());
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<T>() {
                    @Override
                    public void accept(T t) throws Exception {
                        try {
                            callback.doMainTask(t);
                        }catch (Exception e){

                        }
                    }
                });
    }


}
